//
//  CZHomeViewController.swift
//  crkWeibo
//
//  Created by 陈荣科 on 15/12/16.
//  Copyright © 2015年 crk. All rights reserved.
//

import UIKit
import SVPullToRefresh

///cell的缓存标识
enum CZStatusCellReuseIdentifier: String {

    case StatusNormalCell = "StatusNormalCell"//原创cell标识
    case StatusForwardCell = "StatusForwardCell"//转发cell标识
}

class CZHomeViewController: CZBaseViewController {
    
    
    //MARK: - 属性
    
    ///刷新微博条数头部视图的高度
   let tiplabelHight:CGFloat = 44
    
    ///微博模型数组
    var statuses:[CZStatus]?{
    
        didSet{
        
            //刷新数据
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //判断是否登录
        if !CZUserAccount.userLogin{
        
            return
        }
        setupNav()
        
//        CZNetworkTool.sharedInstance.loadStatus { (result, error) -> () in
//            print("result:\(result)")
//        }
        prepareTableView()
        
        //tableView自带一个刷新控件
        refreshControl = CZRefreshControl()
        
        ///MARK: -  刷新加载微博数据
        //刷新控件监听下拉事件
        refreshControl?.addTarget(self, action: "loadNewStatus", forControlEvents: UIControlEvents.ValueChanged)
        
        //主动进入刷新状态，只会让刷新控件界面显示刷新，并不会主动出发UIControlEvents.ValueChanged事件
        refreshControl?.beginRefreshing()
        //主动触发UIControlEvents.ValueChanged
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
        
        }
    
    ///显示下拉刷新的微博条数
    private func showTipView(count: Int) {
    
        tipLabel.text = count == 0 ? "没有加载更新微博" : "加载了\(count)条微博数据"
        //添加tiplabel到导航栏下面
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        //动画
        UIView.animateWithDuration(1.25, animations: { () -> Void in
            self.tipLabel.frame.origin.y = self.tiplabelHight
            }) { (_) -> Void in
                //tipLabl移上去
                UIView.animateWithDuration(1.25, delay: 0.25, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -(self.tiplabelHight + 20)
                    }, completion: { (_) -> Void in
                        //移除tipLabel
//                        self.tipLabel.removeFromSuperview()
                        print("动画完成")
                })
        }
    }
    
    //刷新微博，加载数据
    func loadNewStatus() {
    
        let since_id = statuses?.first?.id ?? 0
        let max_id = 0
        //1、调用微博模型来加载微博数据
        //2、调用闭包
        CZStatus.mLoadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            
            //关闭刷新界面(结束刷新)
            self.refreshControl?.endRefreshing()
            if error != nil{
                print("加载微博数据出错")
                return
            }
            
            let count = statuses?.count ?? 0
            
            //下拉刷新多少条微博
            if since_id > 0 {
                self.showTipView(count)
            }
            //判断statuses是否加载到最新数据
            if count == 0 {
            
                print("没有加载到数据")
                return
            }
            if since_id > 0 {
                //总微博数 = 旧的微博数 + 最新加载的微博数
               self.statuses = statuses! + self.statuses!
                print("下拉 加载微博数据 statuses: \(statuses?.count)")
            }else {//第一次加载20条微博数
                self.statuses = statuses
                print("第一次 加载微博数据 statuses: \(statuses?.count)")
                //需要显示上啦加载更多的菊花
                self.tableView.showsInfiniteScrolling = true
            }
            print("总共多少条微博：\(self.statuses?.count)")
        }
    
    }
    func loadMoreStatus() {
    
        let since_id = 0
        let max_id = statuses?.last?.id ?? 0
        
        CZStatus.mLoadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            
            if error != nil {
            
                print("加载微博数据出错")
                return
            }
            let count = statuses?.count
            //判断是否加载到微博数
            if count == 0 {
            
                print("没有加载到更多的微博")
                return
            }
            if max_id > 0 {
            
                self.statuses = self.statuses! + statuses!
                print("上拉加载更多微博数据：\(count)")
            }
            print("总共多少条微博：\(self.statuses?.count)")
        }
        
    }
    
   private func prepareTableView() {
    
        
        //设置cell预估行高
        tableView.estimatedRowHeight = 200
        
        //注册原创cell
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusNormalCell.rawValue)
        //注册转发cell
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusForwardCell.rawValue)

        // 去掉cell的分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    
        //不添加这个闭包tableview不会出现菊花，只有添加闭包，当拖动到最后一个cell是会出现菊花
        //添加上拉加载更多数据的时间(闭包)，当拖动到最后一个cell时，调用这个闭包
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            print("加载更多数据")
            
            //加载更多数据
            self.loadMoreStatus()
        }
        //现不现实上啦加载更多的菊花
        tableView.showsInfiniteScrolling = false
    }
    
    func setupNav() {
    
        //设置导航栏的左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        
        //因为图片要再右边，系统的button不符合，所以要自定义button
        let title = CZUserAccount.userAccount?.screen_name ?? "没有用户名"
        
        let titleButton = CZHomeTitleButton(title: title, imageName: "navigationbar_arrow_down")
    
        navigationItem.titleView = titleButton
        
        //添加点击事件
        titleButton.addTarget(self, action: "homeTitleButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = titleButton
        
        
        
    }
    

    ///标题点击事件
    func homeTitleButtonClick(button: UIButton){
    
//        print("点击了按钮")
        //按钮的状态设置
        button.selected = !button.selected

        //代码抽取
        UIView.animateWithDuration(0.5) { () -> Void in
            
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI-0.0001)) : CGAffineTransformIdentity
        }
    }
    
    //MARK: - tableView数据源代理
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    ///设置cell的行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        
        let status = self.statuses![indexPath.row]
        
        //判断是否有行高
        if status.height != nil {
        
            //直接返回行高
            return status.height!
        }
        
        let cellId = status.cellId()
        let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
        
        let height = cell.rowHeight(status)
        status.height = height
//        print("cell的行高：\(height)")
        return status.height!
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //取出对应哪个的模型
        let status = statuses![indexPath.row]
        let cellId = status.cellId()
        
        let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
        
        
        //设置cell的微博模型
        cell.status = status
        
        //设置微博的正文内容
//        cell.textLabel?.text = status.text
        
        return cell
    }
    
    ///刷新微博条数的头部view
    private lazy var tipLabel: UILabel = {
        //定义label
        let tipLabel = UILabel(frame: CGRect(x: 0, y:-(self.tiplabelHight + 20), width: UIScreen.mainScreen().bounds.width, height: self.tiplabelHight))
        
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.font = UIFont.systemFontOfSize(16)
        tipLabel.textAlignment = NSTextAlignment.Center

        return tipLabel
    }()

}
